package org.puremvc.as3.apps.flex.appskeleton.shell.model
{
	import mx.rpc.IResponder;
	
	import org.osflash.thunderbolt.Logger;
	import org.puremvc.as3.apps.flex.appskeleton.shell.model.business.LoadXMLDelegate;
	import org.puremvc.as3.apps.flex.appskeleton.shell.model.helpers.XmlResource;
	import org.puremvc.as3.multicore.patterns.proxy.Proxy;
	import org.puremvc.as3.multicore.utilities.startupmanager.controller.StartupResourceFailedCommand;
	import org.puremvc.as3.multicore.utilities.startupmanager.controller.StartupResourceLoadedCommand;
	import org.puremvc.as3.multicore.utilities.startupmanager.interfaces.IStartupProxy;
	import org.puremvc.as3.multicore.utilities.startupmanager.model.StartupMonitorProxy;
	import org.puremvc.as3.multicore.utilities.startupmanager.model.StartupResourceProxy;
	
	public class ConfigProxy extends Proxy implements IStartupProxy,IResponder
	{		
		public static const NAME : String = "ConfigProxy";
		
		public static const CONFIG_LOAD_SUCCESS = "configLoadSuccess";
		public static const CONFIG_LOAD_FAILURE = "configLoadFailure";
		
		private var startupResourceProxy:StartupResourceProxy;
		
		public function ConfigProxy(data:Object = null)
		{
			super(NAME, data);
			Logger.info("ConfigProxy()");
		}
		
		override public function onRegister():void
		{
			startupResourceProxy = new StartupResourceProxy(NAME+"StartupResourceProxy", this);
			facade.registerProxy(startupResourceProxy);

			startupMonitorProxy.addResource(startupResourceProxy);
			
			facade.registerCommand(CONFIG_LOAD_SUCCESS, StartupResourceLoadedCommand);
			facade.registerCommand(CONFIG_LOAD_FAILURE, StartupResourceFailedCommand);
		}
		public function load():void
		{
			Logger.info(NAME + ": load()");
			data = new Object();
			var delegate : LoadXMLDelegate = new LoadXMLDelegate(this, 'assets/config.xml');
			delegate.load();
		}
		
		public function result( rpcEvent : Object ) : void
		{
			XmlResource.parse(data, rpcEvent.result);
			
			sendNotification(CONFIG_LOAD_SUCCESS, NAME);
		}
		
		public function fault( rpcEvent : Object ) : void 
		{
			//sendNotification( ApplicationFacade.LOAD_CONFIG_FAILED, ApplicationFacade.ERROR_LOAD_FILE );
			sendNotification(CONFIG_LOAD_FAILURE, NAME);
		}
		
		public function getValue(key:String):String
		{
			return data[key.toLowerCase()];
		}
		
		public function getStartupResourceProxy():StartupResourceProxy
		{
			return startupResourceProxy;
		}
		
		private function get startupMonitorProxy():StartupMonitorProxy
		{
			return facade.retrieveProxy(StartupMonitorProxy.NAME) as StartupMonitorProxy;
		}
	}
}